package day11;

import java.io.*;
import java.net.Socket;

/**
 * @author oldliu
 * @since 1.0
 */
public class FileSendThread extends Thread {
    private final Socket s;

    public FileSendThread(Socket s){
        this.s=s;
    }
    public static final String FOLDER="E:\\java_workspace\\hbuilderproj\\java82pre\\java82pre\\image";
    @Override
    public void run() {
        try {
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            //1:读一个文件名
            BufferedReader br=new BufferedReader(new InputStreamReader(in));
            String fileName=br.readLine();//当前线程进入等待状态
            File file=new File(FOLDER,fileName);//文件不在，不会有异常
            //输出的第一个字节作为是否存在的标志
            if(file.exists()==false||file.canRead()==false){
                out.write(0);//不存在
            }else{
                out.write(1);//存在
                FileInputStream fin=new FileInputStream(file);
                //byte b[]=new byte[fin.available()];
                //int len=fin.read(b);//一步读完
                byte b[]=new byte[1024];
                int len=0;
                while ((len=fin.read(b))>-1){
                    out.write(b,0,len);
                }
            }
            out.flush();
            System.out.println(s+" over");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                s.close();
            } catch (IOException e) {
            }
        }

    }
}
